<template>
  <div class="customer-info-record">
    <template v-if="recordPage.list.length">
      <div class="customer-timeline" :style="timelineStyle" ref="timeline">
        <base-timeline
          :data="recordPage.list"
          :record-render="renderRecord"
          :loading="recordLoading"
          :loadmore="recordPage.hasNextPage"
          @load="loadmore"
        />
      </div>
      <div
        class="customer-quick-comment"
        v-if="editComment"
        :style="commentStyle"
      >
        <biz-comment
          ref="comment"
          @inputStateChange="inputStateChange"
          :placeholder="$t('common.base.tip.inputCommentContent')"
          :submit-text="$t('common.base.submit')"
          @submit="createRemark"
          :disabled="commentPending"
          autofocus
          user-search-url="/message/user/lists"
          :search-params="{ seeAllOrg: true }"
        ></biz-comment></div
    ></template>
    <template v-else>
      <no-data-view :notice-msg="$t('common.base.noData')"></no-data-view>
    </template>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import Page from '@model/Page';
import {
  queryCommodityDynamic,
  addCommodityRemark,
} from '@src/api/PortalApi.ts';
import NoDataView from '@src/component/common/NoDataViewNew';
import { translateAction } from '@src/util/record'
import { t } from '@src/locales'

function createAttachmentDom(h, attachments) {
  return attachments && attachments.length > 0 ? (
    <div class="base-timeline-attachment base-file__preview">
      {attachments.map(item => (
        <base-file-item
          Source={attachments}
          file={item}
          key={item.id}
          readonly
          size="small"
        />
      ))}
    </div>
  ) : (
    ''
  );
}

export default {
  props: {
    shareData: {
      type: Object,
      default: () => ({}),
    },
    goodsId: {
      type: String,
      default: '',
    },
    collapseDirection: {
      type: String,
      default: '',
    },
  },
  emits: ['changeRecordCount'],
  components: {
    NoDataView,
  },
  data() {
    return {
      isOpenData,
      commentPending: false,
      recordLoading: false, // loading 状态
      recordPage: new Page(), // 页面数据
      params: {
        id: '',
        pageNum: 1,
        pageSize: 15,
      },
      inputState: false,
    };
  },
  computed: {
    /** 添加备注权限 */
    editComment() {
      // return this.allowEditProduct && this.allowOperate;
      return false;
    },
    commentStyle() {
      if (this.collapseDirection == 'left') {
        return 'width:calc(100% - 177px)';
      } else if (this.collapseDirection === '') {
        return 'width:calc(50% - 30px)';
      }
      return 'width:70%;max-width:calc(100% - 445px);bottom:0;';
    },
    timelineStyle() {
      if (this.inputState) return 'padding-bottom: 170px;';

      if (this.editComment) return 'padding-bottom: 125px;';

      return 'padding-bottom: 70px;';
    },
  },
  mounted() {
    this.initRecord();
  },
  methods: {
    // 初始化信息动态
    initRecord() {
      this.params.pageNum = 1;
      this.searchRecord();
    },
    /** 抓取信息动态 */
    fetchRecord(params) {
      return queryCommodityDynamic(params);
    },
    // 查询信息动态
    async searchRecord() {
      try {
        this.recordLoading = true;
        this.params.id = this.goodsId;
        const { code, data } = await this.fetchRecord(this.params);

        if (code !== '200') {
          this.recordLoading = false;
          return this.$message.error(this.$t('goods.tips.errorTip'));
        }

        this.recordLoading = false;
        this.recordPage.list = [];
        this.recordPage.merge(data);
        this.$emit('changeRecordCount', data.total);
      } catch (error) {
        this.recordLoading = false;
        console.error(`searchRecord ${error}`);
      }
    },
    /** 添加备注 */
    async createRemark(form) {
      try {
        this.commentPending = true;
        let params = {
          commodityId: this.goodsId,
          remark: form.content,
        };

        const { code } = await addCommodityRemark(params);

        if (code !== '200') {
          this.commentPending = false;
          return this.$message.error(this.$t('goods.tips.addError'));
        }

        this.commentPending = false;
        this.$refs.comment.reset();
        this.initRecord();
        this.$nextTick(() => {
          this.$refs.timeline.scrollTop = 0;
        });

        this.commentPending = false;
      } catch (e) {
        this.commentPending = false;
        console.error(e);
      }
    },
    // 加载更多
    async loadmore() {
      try {
        this.params.pageNum++;
        this.recordLoading = true;

        const { code, data } = await this.fetchRecord(this.params);

        if (code !== '200') {
          this.recordLoading = false;
          return this.$message.error(this.$t('goods.tips.errorTip'));
        }

        this.recordLoading = false;
        this.recordPage.merge(data);
      } catch (error) {
        this.recordLoading = false;
        console.error(`goods template record loadmore err ${error}`);
      }
    },
    /** 删除备注 */
    async deleteRemark(record) {
      try {
        if (!(await platform.confirm('您确认删除该备注吗？'))) return;

        // const result = await productTemplateDeleteRecord({ id: record.id });
        // const isSucc = result.status == 0;

        // this.$platform.notification({
        //   title: `删除备注${isSucc ? '成功' : '失败'}`,
        //   message: !isSucc && result.message,
        //   type: isSucc ? 'success' : 'error',
        // });

        // if (isSucc) this.initRecord();
      } catch (e) {
        console.error('goods template deleteRemark  err', e);
      }
    },
    /** 根据记录的action渲染对应的内容，支持jsx和render函数 */
    renderRecord(h, item) {
      let {
        action,
        userName,
        showInOwn,
        content,
        attachments,
        primaryName,
        staffId,
        userId,
      } = item;

      if (action == '备注') {
        return [
          <i18n path="common.record.task.somebodyAddRemark" class="main-info" tag="h5">
            <span place="operator">{this.renderUserName(userName, staffId, userId)}</span>
          </i18n>,
          content.isDelete == 'true' ? (
            <i18n path="common.record.task.somebodyDeleteRemark" class="text-danger" tag="p">
              <span place="operator">
                {this.renderUserName(content.deleteUserName, content.deleteUserStaffId)}
              </span>
              <span place="time">{content.deleteTime}</span>
            </i18n>
          ) : (
            [
              <p class="pre-line secondary-info">
                <biz-comment-html
                  html={content.updateContent}
                ></biz-comment-html>
              </p>,
              createAttachmentDom(h, attachments),
            ]
          ),
        ];
      }
      if (action == '删除') {
        return [
          <h5>
            {this.renderUserName(userName, staffId, userId)} {translateAction(action)}{' '}
            {content ? (content.updateFields ? content.updateFields : '') : ''}
          </h5>,
          createAttachmentDom(h, attachments),
        ];
      }

      return [
        <h5>
          {this.renderUserName(userName, staffId, userId)} {translateAction(action)} {t('common.base.goods')}。
        </h5>,
        content ? (
          content.updateFields ? (
            <p class="secondary-info">{t('common.base.modifyField')}：{content.updateFields}</p>
          ) : (
            ''
          )
        ) : (
          ''
        ),
        createAttachmentDom(h, attachments),
      ];
    },
    /**
     * 同时满足以下条件允许删除该记录
     * 1. 该记录没有被删除
     * 2. 产品编辑权限（PRODUCT_EDIT）值为3 或者 是创建人
     * 3. 该客户没有被删除
     */
    allowDeleteRecord(item) {
      let isDelete = item.content && item.content.isDelete == 'true';
      let authorities = this.authorities;
      let user = this.loginUser;
      let isCreator = item.userId == user.userId;

      return (
        !isDelete &&
        ((authorities['PRODUCT_EDIT'] && authorities['PRODUCT_EDIT'] == 3) ||
          isCreator) &&
        this.allowOperate
      );
    },
    renderUserName(userName, staffId, userId) {
      if (userId) {
        if (isOpenData && staffId)
          return (
            <strong class="user-card-triggle" v-user={userId}>
              {<open-data type="userName" openid={staffId}></open-data>}
            </strong>
          );
        return (
          <strong class="user-card-triggle" v-user={userId}>
            {userName}
          </strong>
        );
      }
      if (isOpenData && staffId)
        return (
          <strong>
            {<open-data type="userName" openid={staffId}></open-data>}
          </strong>
        );
      return <strong>{userName}</strong>;
    },
    inputStateChange(val) {
      this.inputState = val;
    },
  },
};
</script>

<style lang="scss">
.customer-info-record {
  height: 100%;
  display: flex;
  flex-flow: column nowrap;

  h5 {
    margin-bottom: 5px;
    .icon-address {
      margin-left: 5px;
    }
  }

  .private {
    @include fontColor();
    .iconfont {
      font-size: 14px;
      margin: 0 6px;
    }
  }

  .secondary-info {
    margin-top: 8px;
  }

  .error-info {
    color: #e51c23;
  }
}

.customer-timeline {
  padding-top: 15px;
  padding-right: 15px;

  flex: 1;
}
</style>
